let PublicPostHandler = function () {
    let csrf_token = $("meta[name='csrf-token']").attr("content");
    const {createEditor, createToolbar} = window.wangEditor

    const editorConfig = {
        placeholder: '输入内容...',
        onChange(editor) {
            const html = editor.getHtml()
            console.log('editor content', html)
        },
    }

    editorConfig.MENU_CONF = {}
    editorConfig.MENU_CONF['uploadImage'] = {
        server: '/post/image_upload/',
        fieldName: 'image',
        maxFileSize: 5 * 1024 * 1024,
        maxNumberOfFiles: 10,
        allowedFileTypes: ['image/*'],
        headers: {
            Accept: 'text/x-json',
            "X-CSRFToken": csrf_token,
        },
        withCredentials: true,
        timeout: 5 * 1000,
    }

    const editor = createEditor({
        selector: '#editor-container',
        html: '<p><br></p>',
        config: editorConfig,
        mode: 'default', // or 'simple'
    })
    this.editor = editor;

    const toolbarConfig = {}

    const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    })
}

PublicPostHandler.prototype.listenSubmitEvent = function () {
    let that = this;
    $("#submit-btn").on("click", function (event) {
        event.preventDefault();
        let title = $("input[name='title']").val();
        let board_id = $("select[name='board_id']").val();
        const content = that.editor.getHtml()
        csrf_ajax.post({
            url: "/post/public/",
            data: {title, board_id, content},
            success: function (result) {
                if (result['code'] === 200) {
                    let data = result['data'];
                    let post_id = data['id'];
                    window.location = "/post/detail/" + post_id;
                } else {
                    alert(result['message']);
                }
            }
        });
    });
}

PublicPostHandler.prototype.run = function () {
    this.listenSubmitEvent();
}


$(function () {
    let handler = new PublicPostHandler();
    handler.run();
});